package com.longtxt.powerband.core

import com.longtxt.powerband.models.DeviceItem
import java.util.Collections

class SimpleBluetoothLeDeviceStore {
    private val mDeviceMap = HashMap<String, DeviceItem>()
    val size: Int
        get() = mDeviceMap.size
    fun addDevice(result: DeviceItem) {
        mDeviceMap[result.mac] = result
    }

    fun clear() {
        mDeviceMap.clear()
    }

    val deviceList: List<DeviceItem>
        get() = getSortedDeviceList()

    val deviceByMac = { mac: String ->
        mDeviceMap[mac]
    }

    private fun getSortedDeviceList(): List<DeviceItem> {
        val methodResult: List<DeviceItem> = ArrayList(mDeviceMap.values)
        Collections.sort(methodResult, DEFAULT_COMPARATOR)
        return methodResult
    }

    private class DeviceRssiComparator : Comparator<DeviceItem> {
        override fun compare(arg0: DeviceItem, arg1: DeviceItem): Int {
            return arg1.rssi.compareTo(arg0.rssi)
        }
    }

    companion object {
        private val DEFAULT_COMPARATOR = DeviceRssiComparator()
    }
}